import click
from flask.cli import AppGroup
from app.models.user import User
from app.models.category import Category
from app.models.article import Article
from app.models.role import Role
from app.extensions import db
from faker import Faker
import random


def register_cli(app):
    init_cli = AppGroup('init', short_help='初始化工作')
    app.cli.add_command(init_cli)

    @init_cli.command(short_help='生成管理员')
    @click.option('--username', default='admin', help='账号')
    @click.option('--password', default='123456', help='密码')
    def admin(username, password):
        if not Role.query.first():
            print('初始化角色')
            Role.init_role()

        if User.query.filter_by(username=username).first():
            raise '账号已经生成，不需要重复生成！'

        user = User(username=username, password=password, nickname='江先生')
        db.session.add(user)
        db.session.commit()
        click.echo('成功生成账号:{}, 密码:{}'.format(username, password))

    @init_cli.command(short_help='生成虚拟数据')
    def fake_context():
        fake = Faker('zh_CN')
        for i in range(6):
            category = Category(title=fake.word())
            db.session.add(category)
        db.session.commit()

        for i in range(50):
            article = Article(
                cid=random.choice(Category.query.all()).id,
                title=fake.sentence(),
                content=fake.text(),
                url=fake.url(),
                created_at=fake.future_datetime()
            )
            db.session.add(article)

        db.session.commit()
